<?php
/**
 * 资讯
 */
namespace App\Service;

use Phalcon\Di;
use App\Models\EwNewsOrig;
use App\Models\EwNews;
use App\Models\EwNewsTopic;
use App\Util\Fun;
use App\Models\EwNewsrecmd;
class NewsOrigService  extends BaseService
{
	const DISPLAY_TRUE = 1;		//显示标识：是
	const DISPLAY_FALSE = 0;	//显示标识：否
	const DEL_TRUE = 1;			//删除标识：是
	const DEL_FALSE = 0;		//删除标识：否

	const TYPE_WORD  = 1;//纯文字
	const TYPE_PIC   = 2;//单图+文字
	const TYPE_PICS  = 3;//多图+文字
	const TYPE_VIDEO = 4;//视频+文字
	const TYPE_ALBUM = 5;//相册+文字
	const TYPE_ADS   = 6;//单图+标题 大图广告

	const CONT_PURE  = 1;//非广告
	const CONT_HFIVE = 2;//H5广告
	const CONT_APP   = 3;//Appstore广告
	const CONT_WAKE  = 4;//App唤醒广告

	/**
	 * [getNewsAll 获取原创新闻及实时新闻合并列表 2017-10-26+]
	 * @param  [type] $params [description]
	 * @return [type]         [description]
	 */
	public static function getNewsAll($params, $count = FALSE)
	{
		$sql = 
			'SELECT 10 AS groupId,o.id AS go_url,o.id AS three_url,o.is_self,
			0 AS is_collect,0 AS is_praise,
			o.city_id,o.id,o.title,IFNULL(o.tags,"") AS tags,
			o.topic_sign,o.sub_type AS sub_type,
			o.content,o.summary,
			o.type_id,o.thumb,o.sources,o.visit,o.comment,o.create_time
			FROM ew_news_orig AS o 
			WHERE sub_type = ' . $params->sub_type . '  AND is_display = 1 AND is_del = 0
			UNION ALL
			SELECT 2 AS groupId,n.id as go_url,n.three_url AS three_url,n.is_self,
			0 AS is_collect,0 AS is_praise,
			n.city_id,n.id,n.title,"" AS tags,
			0 AS topic_sign,n.sub_type AS sub_type,
			n.content,n.summary,
			n.type_id,n.thumb,n.sources,n.visit,n.comment,n.create_time
			FROM ew_news AS n
			WHERE sub_type = ' . $params->sub_type . '  AND city_id in (0,1,' . $params->city_id . ') AND is_display = 1 AND is_del = 0
			ORDER BY create_time DESC
			LIMIT ' . ($params->p-1)*$params->page_num . ',' . $params->page_num;
		if ($count)
			$sql = 
			'SELECT a.co1 + b.co2 AS counts FROM (SELECT COUNT(*) AS co1 FROM ew_news_orig AS o WHERE sub_type = ' . $params->sub_type . ') AS a,
			(SELECT COUNT(*) AS co2 FROM ew_news AS n WHERE sub_type = ' . $params->sub_type . ') AS b';

		$data = (new Fun)->db_execute($sql);
		return $data;
	}
	/**
	 * [getNewsList 获取原创新闻列表 topic_sign >= 0 topic_sign = -1 栏目新闻]
	 * @param  [type] $params [description]
	 * @return [type]         [description]
	 */
	public static function getNewsList($params)
	{
		$sql = 'SELECT 10 AS groupId,n.id AS go_url,n.is_self,"项目动态" AS project_name,
			0 AS is_collect,0 AS is_praise,
			n.id,n.topic_id,n.title,IFNULL(n.tags,"") AS tags,
			IF(topic_id = 0,id,topic_id) AS topic_group,n.news_type,n.topic_sign,
			n.content,n.summary,
			n.type_id,n.thumb,n.sources,n.visit,n.comment,n.create_time,IFNULL(n.index_by,0) AS index_by,IFNULL(n.reco_by,0) AS reco_by,id AS topic FROM ew_news_orig AS n
		where city_id in (0,1,' . $params->city_id . ') AND is_display = 1 AND is_del = 0 AND topic_sign >= 0
		AND news_type = "' . $params->news_type . '"
		ORDER BY id DESC
		LIMIT ' . ($params->p-1)*$params->page_num . ',' . $params->page_num;
		$data = (new Fun)->db_execute($sql);
		return $data;
	}

	/**
	 * [getTopicList 获取项目新闻 topic_sign = 1]
	 * @param  [type] $params [description]
	 * @return [type]         [description]
	 */
	public static function getTopicList($params, $count = FALSE)
	{
		$sql = 'SELECT 10 AS groupId,n.id AS go_url,n.is_self,"项目动态" AS project_name,
			0 AS is_collect,0 AS is_praise,
			n.id,n.topic_id,n.title,IFNULL(n.tags,"") AS tags,
			IF(topic_id = 0,id,topic_id) AS topic_group,n.news_type,n.topic_sign,
			n.content,n.summary,
			n.type_id,n.thumb,n.sources,n.visit,n.comment,n.create_time,IFNULL(n.index_by,0) AS index_by,IFNULL(n.reco_by,0) AS reco_by,id AS topic FROM ew_news_orig AS n
		WHERE city_id in (0,1,' . $params->city_id . ') AND is_display = 1 AND is_del = 0 AND topic_sign = 1
		AND news_type = "' . $params->news_type . '"
		ORDER BY id DESC
		LIMIT ' . ($params->p-1)*$params->page_num . ',' . $params->page_num;

		if ($count)
			$sql = 'SELECT COUNT(id) AS counts FROM ew_news_orig WHERE city_id in (0,1,' . $params->city_id . ') AND is_display = 1 AND is_del = 0 AND topic_sign = 1';

		$data = (new Fun)->db_execute($sql);
		return $data;
	}

	public static function getTopic($id)
	{
		$sql = 'SELECT program,ids FROM ew_news_topic
		WHERE topic_id = ' . $id . '
		ORDER BY order_by DESC';

		$data = (new Fun)->db_execute($sql);
		return $data;
	}

	public static function getNewsListIds($ids)
	{
		$sql = 'SELECT 10 AS groupId,n.id AS go_url,n.is_self,"项目动态" AS project_name,
			0 AS is_collect,0 AS is_praise,
			n.id,n.topic_id,n.title,IFNULL(n.tags,"") AS tags,
			n.id AS topic_group,n.news_type,n.content,n.summary,
			n.type_id,n.thumb,n.sources,n.visit,n.comment,n.create_time,0 AS index_by,0 AS reco_by,id AS topic FROM ew_news_orig AS n
		where n.id in (' . $ids . ')';

		$data = (new Fun)->db_execute($sql);
		return $data;
	}

	/**
	 * [getRecoList 通过target_id获取相关推荐]
	 * @param  [type] $params [description]
	 * @return [type]         [description]
	 */
	public static function getRecoList($params)
	{
		
		//target_id 获取相关推荐列表
		if (isset($params->target_id) && $params->target_id){
			$arr = new \stdClass();
			$arr->table_id = self::getTableId();
			$arr->list_id  = $params->target_id;
			$data = RecoService::getRecoList($arr);
			
			$id_str = implode(',', $data);
			
			if (count($data) > 0){
				$sql = 'SELECT 10 AS groupId,n.id as go_url,n.is_self,"项目动态" AS project_name,
					0 AS is_collect,0 AS is_praise,
					n.id,n.topic_id,n.title,IFNULL(n.tags,"") AS tags,
					IF(topic_id = 0,id,topic_id) AS topic_group,
					n.content,n.summary,
					n.type_id,n.thumb,n.sources,n.visit,n.comment,n.create_time,IFNULL(n.index_by,0) AS index_by,IFNULL(n.reco_by,0) AS reco_by,id AS topic FROM ew_news_orig AS n
					where is_display = 1 AND is_del = 0 AND n.id in ('. $id_str .')
					ORDER BY id DESC
					LIMIT ' . ($params->p-1)*$params->page_num . ',' . $params->page_num;
				return (new Fun)->db_execute($sql);
			}else{
				return self::getNewsList($params);
			}
		}else{
			return self::getNewsList($params);
		}
	}

	/**
	 * [getTopicRecoList 通过target_id获取相关推荐]
	 * @param  [type] $params [description]
	 * @return [type]         [description]
	 */
	public static function getTopicRecoList($params)
	{
		
		//target_id 获取相关推荐列表
		if (isset($params->target_id) && $params->target_id){
			$arr = new \stdClass();
			$arr->table_id = self::getTableId();
			$arr->list_id  = $params->target_id;
			$data = RecoService::getRecoList($arr);
			
			$id_str = implode(',', $data);
			
			if (count($data) > 0){
				$sql = 'SELECT 10 AS groupId,n.id as go_url,n.is_self,"项目动态" AS project_name,
					0 AS is_collect,0 AS is_praise,
					n.id,n.topic_id,n.title,IFNULL(n.tags,"") AS tags,
					IF(topic_id = 0,id,topic_id) AS topic_group,
					n.content,n.summary,
					n.type_id,n.thumb,n.sources,n.visit,n.comment,n.create_time,IFNULL(n.index_by,0) AS index_by,IFNULL(n.reco_by,0) AS reco_by,id AS topic FROM ew_news_orig AS n
					where is_display = 1 AND is_del = 0 AND n.id in ('. $id_str .')
					ORDER BY id DESC
					LIMIT ' . ($params->p-1)*$params->page_num . ',' . $params->page_num;
				return (new Fun)->db_execute($sql);
			}else{
				return self::getTopicList($params);
			}
		}else{
			return self::getTopicList($params);
		}
	}

	/**
	 * [getList 列表 APP]
	 * @param  [type]  $params [description]
	 * @param  boolean $count  [description]
	 * @return [type]          [description]
	 */
    public static function getList($params, $count = FALSE, $topic_id = NULL)
    {
    	$member_id = property_exists($params,'member_id') ? $params->member_id : 0;
		$builder = new \Phalcon\Mvc\Model\Query\Builder();
		$builder->columns([self::getTableId() . ' as groupId,n.id as go_url,n.is_self,
			0 AS is_collect,0 AS is_praise,
			n.id,n.topic_id,n.title,IFNULL(n.tags,"") AS tags,
			IF(topic_id = 0,id,topic_id) AS topic_group,
			n.content,n.summary,
			n.type_id,n.thumb,n.sources,n.visit,n.comment,n.create_time,IFNULL(n.index_by,0) AS index_by,IFNULL(n.reco_by,0) AS reco_by,id AS topic']);
		$builder->addFrom("App\Models\EwNewsOrig", 'n');
		// $builder->andWhere("n.is_del = " . self::DEL_FALSE);

		//target_id 获取相关推荐列表
		if (isset($params->target_id) && $params->target_id){
			$arr = new \stdClass();
			$arr->table_id = self::getTableId();
			$arr->list_id  = $params->target_id;
			$data = RecoService::getRecoList($arr);
			if (count($data) > 0){
				$builder->inWhere('n.id', $data);
			}
		}
		//获取专题
		if ($topic_id){
			$builder->andWhere("n.topic_id = ". $topic_id);
			$page_num = 1000;
			$p = 1;
		}else{
			$builder->groupBy('topic_group');
		}

		//title 名称
		if (isset($params->title) && $params->title)
			$builder->andwhere('n.title LIKE "%'.$params->title.'%"');
		
		//city_id
		if (isset($params->city_id) && $params->city_id)
			$builder->andWhere("n.city_id in ( 0 , 1 , " . $params->city_id . " )");

		//tags 
		if (isset($params->tags) && $params->tags)
			$builder->andWhere("n.tags = ". $params->tags);

		//is_display
		if (isset($params->is_display))
			$builder->andWhere("n.is_display = ". $params->is_display);

		//cate_id
		if (isset($params->cate_id) && $params->cate_id)
			$builder->andWhere("n.cate_id = ". $params->cate_id);
		//type_id 1文字,2图左字右3多图,4视频,5相册,6大图广告
		if (isset($params->type_id) && $params->type_id)
			$builder->andWhere("n.type_id = ". $params->type_id);

		

		//count 数量
		if ($count)
			return $builder->getQuery()->execute()->count();

		// $sql = "n.order_by DESC, n.create_time DESC, n.id DESC, n.update_time DESC";
		$sql = "  n.order_by DESC, n.id DESC";//默认获取 首页 - NewsOrig
		if (isset($params->is_reco) && $params->is_reco)//获取推荐 - NewsOrig
			$sql = " n.order_by DESC, n.id DESC";
		//order_by 排序
		if (isset($params->order_by) && $params->order_by)
			$sql = parent::orderBy($params->order_by, $table = "n");

		$builder->orderBy($sql);

		$builder->limit($params->page_num,($params->p-1)*$params->page_num);
		$result = $builder->getQuery();
		return $result->execute();
	}

	/**
	 * [getSearch 列表 后台]
	 * @param  [type]  $params [description]
	 * @param  boolean $count  [description]
	 * @return [type]          [description]
	 */
	public static function getSearch($params, $count = FALSE)
    {
		$builder = new \Phalcon\Mvc\Model\Query\Builder();

		$builder->columns(['n.id,n.id as go_url,n.title,n.tags,
			n.type_id,n.topic_id,n.pics,n.thumb,n.sources,n.visit,n.visit_re,n.comment,n.order_by,n.is_display,n.create_time,n.topic_sign,n.city_id,n.creator_id']);
		$builder->addFrom("App\Models\EwNewsOrig", 'n');
		$builder->andWhere("n.is_del = " . self::DEL_FALSE);

		//position_id 通过position_id 获取后台弹出列表  1 首页
		if (isset($params->position_id) && $params->position_id == 2) //推荐资讯
			$builder->andWhere("n.reco_by  != '2' and n.index_by != '2' AND n.is_display = 1");
		if (isset($params->position_id) && $params->position_id == 1) //新闻
			$builder->andWhere("n.reco_by  != '2' and n.index_by != '2' AND n.is_display = 1");

		//reco_by
		if (isset($params->reco_by))//首页banner列表 reco_by = 2
			$builder->andWhere("n.reco_by = '" . $params->reco_by . "'");

		//index_by
		if (isset($params->index_by))//首页视频列表 index_by = 2
			$builder->andWhere("n.index_by = '" . $params->index_by . "'");

		//city_id
		if (isset($params->city_id) && $params->city_id){
			if (isset($params->creator_id) && $params->creator_id){
				$builder->andWhere("n.city_id =" . $params->city_id . " OR n.creator_id = " . $params->creator_id);
			}else{
				$builder->andWhere("n.city_id =" . $params->city_id . " ");
			}
		}

		//is_display
		if (isset($params->is_display))
			$builder->andWhere("n.is_display = ". $params->is_display);

		//title
		if (isset($params->title) && $params->title)
			$builder->andwhere("n.title LIKE '%" . $params->title . "%'");
		//summary
		if (isset($params->summary) && $params->summary)
			$builder->andwhere("n.summary LIKE '%" . $params->summary . "%'");
		//content
		if (isset($params->content) && $params->content)
			$builder->andwhere("n.content LIKE '%" . $params->content . "%'");
		//author
		if (isset($params->author) && $params->author)
			$builder->andwhere("n.author LIKE '%" . $params->author . "%'");
		//summary
		if (isset($params->summary) && $params->summary)
			$builder->andwhere("n.summary LIKE '%" . $params->summary . "%'");
		//sources
		if (isset($params->sources) && $params->sources)
			$builder->andwhere("n.sources LIKE '%" . $params->sources . "%'");
		//cate_id
		if (isset($params->cate_id) && $params->cate_id)
			$builder->andWhere("n.cate_id = ". $params->cate_id);
		//type_id 1文字,2图左字右,3多图,4视频,5相册,6大图广告
		if (isset($params->type_id) && $params->type_id)
			$builder->andWhere("n.type_id = ". $params->type_id);
	
		//count 数量
		if ($count)
			return $builder->getQuery()->execute()->count();

		$sql = "n.order_by DESC, n.create_time DESC, n.id DESC, n.update_time DESC";
		//order_by 排序
		if (isset($params->order_by))
			$sql = parent::orderBy($params->order_by, $table = "n");

		$builder->orderBy($sql);

		$builder->limit($params->page_num,($params->p-1)*$params->page_num);
		$result = $builder->getQuery();
		return $result->execute();
	}

	/**
	 * [getTableName 获取数据表名称]
	 * @return [type] [description]
	 */
	public static function getTableName()
	{
		$model = new EwNewsOrig;
		return $model->getSource();
	}

	/**
	 * [getTableId 获取数据表Id]
	 * @return [type] [description]
	 */
	public static function getTableId()
	{
		return ConfigsService::getTable(self::getTableName());
	}

	public static function getModel($id = 0)
	{
		return EwNewsOrig::findFirst($id);
	}

	/**
	 * [getRecoInfo 通过id查询数据 相关推荐]
	 * @param  [type] $reco_ids [description]
	 * @return [type]           [description]
	 */
	public static function getRecoInfo($id)
	{

		$arr = new \stdClass();
		$arr->table_id = self::getTableId();
		$arr->list_id  = $id;
		$data = RecoService::getRecoList($arr);
		if(empty($data)) return $data;
		$query = EwNewsOrig::query();
		$query->columns(['id,title,summary,thumb,sources']);
		$query->inWhere('id', $data);
		
		$data = $query->execute();
		if ($data){
			return $data;
		}
	}
	
	/**
	 * [getInfo 通过主键获取详情]
	 * @param  integer $id [description]
	 * @return [type]      [description]
	 */
	public static function getInfo($id = 0, $member_id = NULL)
	{	
		$info = (new EwNewsOrig)->findFirst($id);

		if (!$info)
			return NULL;
		$info = $info->toArray();

		$data = new \stdClass();
		$data->go_url  = "";
		$data->groupId = self::getTableId();
		$data->praise = (string)0;
		$data->is_praise = (string)-1;

		$arr = new \stdClass();
		$arr->table_id = self::getTableId();
		$arr->list_id  = $id;
		$arr->praise   = NULL;
		//获取点赞量
		$data->praise = (string)MemberPraiseService::sum($arr);
		//获取当前用户是否点赞
		if ($member_id){
			$arr->member_id = $member_id;
			$data->is_praise = (string)MemberPraiseService::juge($arr);
		}
		
		foreach ($info as $key => $value) {
			$data->$key = $value;
		}
		
		return $data;
	}

	/**
	 * [count 获取总量]
	 * @return [type] [description]
	 */
	public static function count()
	{
		return EwNewsOrig::count();
	}

	/**
	 * [getStick 置顶]
	 * @param  [type] $id [description]
	 * @return [type]     [description]
	 */
	public static function getStick($id)
	{
		if (isset($id) && $id)
			$raw = EwNewsOrig::findFirst($id);

		if ($raw){
			$max = EwNewsOrig::maximum(['column' => 'order_by']);
			$raw->order_by = $max + 1;
			return $raw->save();
		}
		return NULL;
	}

	/**
	 * [visit 浏览量 +1]
	 * @param  [type] $id [description]
	 * @return [type]     [description]
	 */
	public static function visit($id)
	{
		if (isset($id) && $id)
			$data = EwNewsOrig::findFirst($id);

		if ($data){
			$data->visit = $data->visit + 1;
			return $data->save();
		}

		return NULL;
	}
	
	/**
	 * [display 上架]
	 * @param  [type] $id [description]
	 * @return [type]     [description]
	 */
	public static function display($id)
	{
		if (isset($id) && $id)
			$data = EwNewsOrig::findFirst($id);

		if ($data){
			$data->is_display = $data->is_display ? self::DISPLAY_FALSE : self::DISPLAY_TRUE;
			return $data->save();
		}

		return NULL;
	}

	/**
	 * [delete 移除/恢复数据]
	 * @param  [type] $id [description]
	 * @return [type]     [description]
	 */
	public static function delete($id)
	{
		if (isset($id) && $id)
			$data = EwNewsOrig::findFirst($id);

		if ($data){
			$data->is_del = $data->is_del ? self::DEL_FALSE : self::DEL_TRUE;
			return $data->save();
		}

		return NULL;		
	}

	/**
	 * [delete 彻底删除数据]
	 * @param  [type] $id [description]
	 * @return [type]     [description]
	 */
	public static function forever($id)
	{
		if (isset($id) && $id)
			$row = EwNewsOrig::findFirst($id);

		if ($row && $row->delete()){
			$arr = new \stdClass();
		 	$arr->table_id = self::getTableId();
			$arr->list_id  = $id;
			RecoService::deleteRecoList($arr);
			return TRUE;
		}
		return NULL;
	}

	/**
	 * [beforeSave 保存前预处理 ]
	 * @param  [type] $data [description]
	 * @return [type]       [description]
	 */
	public static function beforeSave($data)
	{
		$config = Di::getDefault()['config'];
		$thumb = $config->imgurl . '/uploads/default.png';
		$type_id = intval($data->type_id);
		//$cont_type = intval($data->cont_type);
		$model = new \stdClass();
		foreach ($data as $key => $value) {
			$model->$key = $value;
		}

		$visit = rand(2000, 20000);
		$city_id_arr = [63,75,169,176];
	    //如果是
	    if (in_array($data->city_id, $city_id_arr))
	        $visit = rand(20000, 40000);

		$model->visit = ( property_exists($data,'visit') && $data->visit > 0) ? $data->visit : $visit;
		$model->news_type = property_exists($data,'news_type') ? $data->news_type : 'putong';
        /*
		//图文混编
		if ($type_id == self::TYPE_WORD || $type_id == self::TYPE_PIC || $type_id == self::TYPE_PICS){
			//根据复文本编辑框中的数据判断图片的张数
			$pattern="/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg]))[\'|\"].*?[\/]?>/"; 
			preg_match_all($pattern,$data->content,$match);

			if (count($match) == 2 && count($match[1]) > 0){
				$model->type_id = count($match[1])>2 ? 3 : 2;//复文本内图片大于2张才将类型更改为多图+文字
				$pics = implode(',', $match[1]);
				$model->thumb = current($match[1]) ? $match[1][0] : $thumb;
			}else{
				$model->type_id = 1;
				$pics = "";
				$model->thumb = $thumb;
			}
			$model->pics = $pics;
			$model->content = isset($data->content) ? $data->content : "";
			$model->album = "";
			$model->duration = "";
			$model->video = "";
		}else if ($type_id == self::TYPE_VIDEO) {//视频 视频缩略图 + 视频 thumb + video +duration
			$model->thumb = isset($data->thumb) ? $data->thumb : $thumb;
			$model->video = isset($data->video) ? $data->video : "";
			$model->duration = isset($data->duration) ? $data->duration : "";
			$model->album = "";
			$model->content = isset($data->content) ? $data->content : "";
		//type_id = 5 相册
		}else if ($type_id == self::TYPE_ALBUM ) {//相册 缩略图 + （图片+文字）* thumb + album
			if (count($data->album) <= 0 )
				return NULL;
			$bigimg = current($data->album);
			$model->duration = "";
			$model->thumb = "";
			$model->video = "";
			$model->thumb = isset($data->album) ? $bigimg->bigimg : $thumb;
			$model->album = isset($data->album) ? $data->album : [];
			$model->album = json_encode($model->album);ntent : "";
			$model->content = "";
		}else if ($type_id == self::TYPE_ADS) {//App大图广告 标题+图片 thumb + title
			$model->thumb = isset($data->thumb) ? $data->thumb : $thumb;
			$model->pics = "";
			$model->content = "";
			$model->album = "";
			$model->duration = "";
			$model->video = "";
		}
        */
		return $model;
	}

	/**
	 * [save 保存]
	 * @param  [type] $data [description]
	 * @return [type]       [description]
	 */
	public static function save($data)
	{
		$data = self::beforeSave($data);

		$row = new EwNewsOrig;
		if (isset($data->id) && $data->id){
			$row = EwNewsOrig::findFirst($data->id);
			//修改新闻是不改变添加时的城市id
			$data->city_id = $row->city_id;
			// $data->visit = ($row->visit > 2000 ) ? $row->visit : $data->visit;
		}

		//置顶
		if (isset($data->is_stick) && $data->is_stick){
			$max = EwNewsOrig::maximum(['column' => 'order_by']);
			$data->order_by = $max + 1;
		}

		if($row && $row -> save((array)$data)) {
		 	//推荐id插入推荐表
		 	$arr = new \stdClass();
		 	$arr->table_id = self::getTableId();
			$arr->list_id  = $row->id;
			$arr->reco_ids = $data->reco_ids;
		 	RecoService::saveRecoList($arr);
		 	return $row;
	    }		
	}

	/**
	 * [setCity 设置原创新闻的city_id = 0]
	 * create_time 2017-11-27
	 * @param [type] $id_arr [description]
	 */
	public static function setCity($id_arr = [])
	{
		if (isset($id_arr) && is_array($id_arr) && count($id_arr) > 0){
			foreach ($id_arr as $id) {
				$raw = EwNewsOrig::findFirst(['id = ' . $id]);
				if ($raw){
					$raw->city_id = 0;
					$raw->save($raw);
				}
			}
		}
	}

	/**
	 * [saveTopic 保存专题的栏目新闻]
	 * @param  [type] $topic_id [专题id]
	 * @param  [type] $program [栏目名称]
	 * @param  [type] $ids [栏目下的id ,分割]
	 * create_time 2017-10-16
	 * @return [type]       [description]
	 */
	public static function saveTopic($data)
	{
		$row = new EwNewsTopic;
		$arr = new \stdClass();
		$arr->topic_id = $data['topic_id'];
		$arr->program  = $data['program'];
		$arr->ids      = $data['ids'];
		$arr->order_by = 0;
		if($row && $row -> save((array)$arr)) {
			return;
		}else{
			var_dump($row->getErrors());
		}
	}

	/**
	 * [deleteTopic 删除专题的栏目新闻]
	 * @param  [type] $topic_id [description]
	 * create_time 2017-10-16
	 * @return [type]           [description]
	 */
	public static function deleteTopic($topic_id)
	{
		$raws = EwNewsTopic::find(['topic_id = ' . $topic_id]);
		if ($raws){
			foreach ($raws as $key => $raw) {
				$id_arr = explode(',', $raw->ids);

				foreach ($id_arr as $key => $id) {
					//恢复栏目新闻为普通新闻
					$row = EwNewsOrig::findFirst($id);
					if ($row){
						$row->topic_sign = 0;
						$row->save();
					}
				}
				$raw->delete();
			}
		}
	}

	/**
	 * [setTopic 设置已推荐为专题栏目新闻的topic_sign = -1]
	 * create_time 2017-10-16
	 * @param [type] $id_arr [description]
	 */
	public static function setTopic($id_arr = [])
	{
		if (isset($id_arr) && is_array($id_arr) && count($id_arr) > 0){
			foreach ($id_arr as $id) {
				$raw = EwNewsOrig::findFirst(['id = ' . $id]);
				if ($raw){
					$raw->topic_sign = -1;
					$raw->save($raw);
				}
			}
		}
	}
	
	/**
	 * 2017-3-28 +
	 * [batchReco 批量 推荐/批量删除 到 推荐列表  首页列表]
	 * @param  [type]  $id_arr [操作的id 数组形式]
	 * @param  integer $action [2推荐到推荐列表 1推荐到首页列表 默认取消推荐]
	 * @return [type]          [description]
	 */
	public static function batchReco($id_arr = [], $action = FALSE )
	{
		//查询最大的order_by
		$max = EwNewsOrig::maximum(['column' => 'order_by']);
		$reco_by  = 0;
		$index_by = 0;
		switch ($action) {
			case 2://推荐到推荐列表
				$reco_by  = 2;
				$index_by = 0;
				$order_by = $max + 1;
				break;

			case 1://推荐到首页列表
				$reco_by  = 0;
				$index_by = 2;
				$order_by = $max + 1;
				break;

			default://取消推荐
				$reco_by  = 0;
				$index_by = 0;
				$order_by = 100;
				break;
		}

		if ($id_arr && is_array($id_arr) && count($id_arr) > 0){
			foreach ($id_arr as $id) {
				$row = EwNewsOrig::findFirst($id);
				$row->reco_by  = $reco_by;
				$row->index_by = $index_by;
				$row->order_by = $order_by;
				$row->save();
			}
		}
	}
    /**
     * 2017-3-28 +
     * [app首页加载推荐新闻方法]
     * @param  map封装参数
     * @return [type]          [description]
     */
    public static function getFirstNewsRecmd($para){
        $sql = "SELECT nr.id,nr.title,nr.go_url,nr.thumb,nr.groupId from ew_newsrecmd nr where nr.city_id in({$para['city_id']})
                and now()<= nr.exp_date ORDER BY id desc limit 2";
        return (new Fun)->db_execute($sql);
    }
    /**
     * [save 保存]
     * @param  [type] $data [description]
     * @return [type]       [description]
     */
    public static function saveNewsRecod($data)
    {

        $row = new EwNewsrecmd;
        if (isset($data->id) && $data->id){
            $row = EwNewsrecmd::findFirst($data->id);

        }
        return $row->save((array)$data);

    }
    public static function getNewsOrgRecIspush($where){
        $sql = "SELECT nr.id,nr.title,nr.go_url,nr.thumb,nr.groupId,nr.exp_date from
              ew_newsrecmd nr where {$where}  ";

        $data = (new Fun)->db_execute($sql);
        return $data;
    }
    public static function getNewsOrgRecmdList($params)
    {
        $where='1=1';
        if(isset($params->city_id)){
            $where.=" and nr.city_id=".$params->city_id;
        }
        $sql = "SELECT nr.id,nr.title,nr.go_url,nr.thumb,nr.groupId,nr.exp_date from
              ew_newsrecmd nr where {$where}  ORDER BY nr.id desc LIMIT " . ($params->p-1)*$params->page_num . ',' . $params->page_num;

        $data = (new Fun)->db_execute($sql);
        return $data;
    }
    public static function removeNewsOrgRecmdRecord($id){
        if (isset($id) && $id)
            $row = EwNewsrecmd::findFirst($id);

        if ($row){
            $row->delete();
            return TRUE;
        }
        return false;
    }
    public static function updateComments($sql){
        Di::getDefault()['dbWrite']->query($sql);
        //$data = (new Fun)->db_execute($sql);
        return '';
    }

}